package com.lkd.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.base.Strings;
import com.lkd.common.VMSystem;
import com.lkd.config.TopicConfig;
import com.lkd.contract.*;
import com.lkd.dao.TaskDao;
import com.lkd.emq.MqttProducer;
import com.lkd.entity.TaskDetailsEntity;
import com.lkd.entity.TaskEntity;
import com.lkd.exception.LogicException;
import com.lkd.feign.UserServiceFeignClient;
import com.lkd.feign.VmServiceFeignClient;
import com.lkd.feign.fallback.VmServiceFallbackFactory;
import com.lkd.http.vo.CancelTaskVo;
import com.lkd.http.vo.TaskDetailsViewModel;
import com.lkd.http.vo.TaskReportInfoVO;
import com.lkd.http.vo.TaskViewModel;
import com.lkd.service.TaskDetailsService;
import com.lkd.service.TaskService;
import com.lkd.utils.JsonUtil;
import com.lkd.vo.Pager;
import com.lkd.vo.UserVO;
import com.lkd.vo.VmVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Service
@Slf4j
public class TaskServiceImpl extends ServiceImpl<TaskDao, TaskEntity> implements TaskService {


    @Autowired
    private VmServiceFeignClient vmServiceFeignClient;
    @Autowired
    private UserServiceFeignClient userServiceFeignClient;
    @Autowired
    private TaskDetailsService taskDetailsService;
    @Autowired
    private StringRedisTemplate redisTemplate;

    /**
     * 分页查询
     *
     * @param pageIndex
     * @param pageSize
     * @param innerCode
     * @param userId
     * @param taskCode
     * @param status
     * @param isRepair
     * @param start
     * @param end
     * @return
     */
    @Override
    public Pager<TaskEntity> search(Long pageIndex, Long pageSize, String innerCode, Integer userId, String taskCode, Integer status, Boolean isRepair, String start, String end) {

//        设置分页
        Page<TaskEntity> ipage = new Page<>(pageIndex, pageSize);
//        设置查询
        LambdaQueryWrapper<TaskEntity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper
                .eq(StringUtils.isNotBlank(innerCode), TaskEntity::getInnerCode, innerCode)
                .eq(userId != null, TaskEntity::getUserId, userId)
                .eq(status != null, TaskEntity::getTaskStatus, status)
                .eq(StringUtils.isNotBlank(taskCode), TaskEntity::getTaskCode, taskCode);
        if (isRepair != null && isRepair) {
//            查询运维工单 ,类型不是补货
            queryWrapper.ne(TaskEntity::getProductTypeId, VMSystem.TASK_TYPE_SUPPLY);
        } else if (isRepair != null && !isRepair) {
//            查询运营工单
            queryWrapper.eq(TaskEntity::getProductTypeId, VMSystem.TASK_TYPE_SUPPLY);
        }
        if (StringUtils.isNotBlank(start)) {
            queryWrapper.gt(TaskEntity::getCreateTime, LocalDate.parse(start, DateTimeFormatter.ISO_DATE));
        }
        if (StringUtils.isNotBlank(end)) {
            queryWrapper.lt(TaskEntity::getCreateTime, LocalDate.parse(end, DateTimeFormatter.ISO_DATE));
        }
//        按照时间倒序
        queryWrapper.orderByDesc(TaskEntity::getCreateTime);
//        分页查询
        Page<TaskEntity> taskEntityPage = page(ipage, queryWrapper);
//        构造返回数据
        return Pager.build(taskEntityPage);

    }

    /**
     * 创建工单
     *
     * @param taskViewModel
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean create(TaskViewModel taskViewModel, Integer assignorId) {

        String innerCode = taskViewModel.getInnerCode();
//        远程调用，获取售后机数据
        VmVO vmVO = vmServiceFeignClient.getvmInfoByInnerCode(innerCode);
        if (vmVO == null) {
            log.error("没有售货机数据");
            throw new LogicException("没有售货机数据");
        }
//        检查工单类型和售货机状态
        checkVmStatus(taskViewModel.getProductType(), vmVO.getVmStatus());

//        检查是否收货机有未完成的同类工单
        hasTask(innerCode, taskViewModel.getProductType());
//        检查分配人员是否存在
        Integer userId = taskViewModel.getUserId();
//        远程调用user服务，获取用户信息
        UserVO userVO = userServiceFeignClient.findById(userId);
        if (userVO == null) {
            log.error("没有人员数据");
            throw new LogicException("没有人员数据");
        }
//        检查人员和售货机的区域是否一致
        if (userVO.getRegionId().longValue() != vmVO.getRegionId().longValue()) {
            log.error("区域数据不一致");
            throw new LogicException("区域数据不一致");

        }
//        新增工单数据
        TaskEntity taskEntity = new TaskEntity();
        taskEntity.setTaskCode(generateCode());
        taskEntity.setTaskStatus(VMSystem.TASK_STATUS_CREATE);
        taskEntity.setCreateType(taskViewModel.getCreateType());
        taskEntity.setInnerCode(innerCode);
        taskEntity.setUserId(userId);
        taskEntity.setUserName(userVO.getUserName());
        taskEntity.setRegionId(vmVO.getRegionId());
        taskEntity.setDescript(taskViewModel.getDesc());
        taskEntity.setProductTypeId(taskViewModel.getProductType());
        taskEntity.setAssignorId(assignorId);
        taskEntity.setAddr(vmVO.getNodeAddr());
        save(taskEntity);
        Long taskId = taskEntity.getTaskId();
//        如果运营工单，新增补货详情
        if (taskViewModel.getProductType().intValue() == VMSystem.TASK_TYPE_SUPPLY.intValue()) {
            List<TaskDetailsViewModel> details = taskViewModel.getDetails();
            if (CollectionUtils.isEmpty(details)) {
                log.error("没有补货数据");
                throw new LogicException("没有补货数据");
            }

            List<TaskDetailsEntity> detailsEntityList = details.stream().map(
                    detail -> {
                        TaskDetailsEntity taskDetailsEntity = new TaskDetailsEntity();
                        BeanUtils.copyProperties(detail, taskDetailsEntity);
                        taskDetailsEntity.setTaskId(taskId);
                        taskDetailsEntity.setSkuId(Long.valueOf(detail.getSkuId()));
                        return taskDetailsEntity;
                    }
            ).collect(Collectors.toList());

            taskDetailsService.saveBatch(detailsEntityList);
        }
//        更新redis的工单数量
        this.updateRedisTaskNum(taskEntity,1L);
        return true;
    }

    /**
     * 接受工单
     * @param taskId
     * @return
     */
    @Override
    public Boolean accept(Long taskId, Integer loginUserId) {
//        查询工单
        TaskEntity taskEntity = getById(taskId);
        if(taskEntity == null){
            log.error("工单不存在");
            throw new LogicException("工单不存在");
        }
//        判断当前登录用户是否可以处理工单
        if(loginUserId.intValue() != taskEntity.getUserId().intValue()){
            log.error("没有权限处理当前工单");
            throw new LogicException("没有权限处理当前工单");
        }
        if(taskEntity.getTaskStatus().intValue() != VMSystem.TASK_STATUS_CREATE.intValue()){
            log.error("工单状态异常");
            throw new LogicException("工单状态异常");
        }
//        修改工单
        LambdaUpdateWrapper<TaskEntity> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper
                .eq(TaskEntity::getTaskId,taskId)
                .eq(TaskEntity::getTaskStatus,VMSystem.TASK_STATUS_CREATE)
                .set(TaskEntity::getTaskStatus,VMSystem.TASK_STATUS_PROGRESS);
        boolean b = update(updateWrapper);
        return b;
    }
    /**
     * 取消，拒绝工单
     * @param taskId
     * @return
     */
    @Override
    public Boolean cancel(Long taskId, Integer loginUserId, CancelTaskVo cancelTaskVo) {
        //        查询工单
        TaskEntity taskEntity = getById(taskId);
        if(taskEntity == null){
            log.error("工单不存在");
            throw new LogicException("工单不存在");
        }
//        判断当前登录用户是否可以处理工单
        if(loginUserId.intValue() != taskEntity.getUserId().intValue()){
            log.error("没有权限处理当前工单");
            throw new LogicException("没有权限处理当前工单");
        }
        if(taskEntity.getTaskStatus().intValue() > VMSystem.TASK_STATUS_PROGRESS){
            log.error("工单状态异常");
            throw new LogicException("工单状态异常");
        }
//        修改工单
//        update tb_task set task_status=3 where task_id=? and task_status<3
        LambdaUpdateWrapper<TaskEntity> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper
                .eq(TaskEntity::getTaskId,taskId)
                .lt(TaskEntity::getTaskStatus,VMSystem.TASK_STATUS_CANCEL)
                .set(TaskEntity::getTaskStatus,VMSystem.TASK_STATUS_CANCEL)
                .set(TaskEntity::getDescript,cancelTaskVo.getDesc());
        boolean b = update(updateWrapper);
        if(b){
//            修改redis中的工单数量 -1
            this.updateRedisTaskNum(taskEntity,-1L);
        }
        return b;
    }
    /**
     * 完成工单
     * @param taskId
     * @return
     */
    @Override
    public Boolean complete(Long taskId, Integer loginUserId) {

//        查询工单
        TaskEntity taskEntity = getById(taskId);
        if(taskEntity == null){
            log.error("工单不存在");
            throw new LogicException("工单不存在");
        }
//        判断当前登录用户是否可以处理工单
        if(loginUserId.intValue() != taskEntity.getUserId().intValue()){
            log.error("没有权限处理当前工单");
            throw new LogicException("没有权限处理当前工单");
        }
        if(taskEntity.getTaskStatus().intValue() != VMSystem.TASK_STATUS_PROGRESS.intValue()){
            log.error("工单状态异常");
            throw new LogicException("工单状态异常");
        }
//        修改工单
        LambdaUpdateWrapper<TaskEntity> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper
                .eq(TaskEntity::getTaskId,taskId)
                .eq(TaskEntity::getTaskStatus,VMSystem.TASK_STATUS_PROGRESS)
                .set(TaskEntity::getTaskStatus,VMSystem.TASK_STATUS_FINISH);
        boolean b = update(updateWrapper);
//       TODO 业务解耦，发送消息到中间件
//        发送运维消息-投放-撤机工单（售后机状态，售货机编号）
//        发送运营消息 （售货机编号，货道编号，商品id，数量）
        sendTaskCompleteMsg(taskEntity);
        return b;

    }

    @Autowired
    private MqttProducer mqttProducer;

    /**
     * 发送运维消息-投放-撤机工单（售后机状态，售货机编号）
     * 发送运营消息 （售货机编号，货道编号，商品id，数量）
     * @param taskEntity
     */
    private void sendTaskCompleteMsg(TaskEntity taskEntity) {
        String innerCode = taskEntity.getInnerCode();
        try {
            if (taskEntity.getProductTypeId() == VMSystem.TASK_TYPE_SUPPLY) {
//            补货工单
                String topic = TopicConfig.VMS_SUPPLY_TOPIC;
                SupplyContract supplyContract = new SupplyContract();
                supplyContract.setInnerCode(innerCode);
//                根据工单查询补货数据
                List<TaskDetailsEntity> taskDetailList = taskDetailsService.getTaskDetailList(taskEntity.getTaskId());
                if(CollectionUtils.isEmpty(taskDetailList)){
                    log.error("获取补货数据失败！");
                    throw new LogicException("获取补货数据失败！");
                }
//                设置补货的货道数据
//                List<SupplyChannel> supplyChannelList = new ArrayList<>();
//                for (TaskDetailsEntity taskDetailsEntity :taskDetailList){
//                    SupplyChannel supplyChannel = new SupplyChannel();
//                    supplyChannel.setChannelCode(taskDetailsEntity.getChannelCode());
//                    supplyChannel.setSkuId(taskDetailsEntity.getSkuId());
//                    supplyChannel.setCapacity(taskDetailsEntity.getExpectCapacity());
//                    supplyChannel.setSkuName(taskDetailsEntity.getSkuName());
//                    supplyChannel.setSkuImage(taskDetailsEntity.getSkuImage());
//                    supplyChannelList.add(supplyChannel);
//                }
                List<SupplyChannel> supplyChannelList = taskDetailList.stream().map(detail -> {
                    SupplyChannel supplyChannel = new SupplyChannel();
                    supplyChannel.setChannelCode(detail.getChannelCode());
                    supplyChannel.setSkuId(detail.getSkuId());
                    supplyChannel.setCapacity(detail.getExpectCapacity());
                    supplyChannel.setSkuName(detail.getSkuName());
                    supplyChannel.setSkuImage(detail.getSkuImage());
                    return supplyChannel;
                }).collect(Collectors.toList());
                supplyContract.setSupplyData(supplyChannelList);
                mqttProducer.send(topic, 2, supplyContract);
            } else {
//            运维工单
                if (taskEntity.getProductTypeId() == VMSystem.TASK_TYPE_REPAIR) {
                    log.info("维修工单，什么都不做，结束");
                    return;
                }
                String topic = TopicConfig.VMS_COMPLETED_TOPIC;
                TaskCompleteContract taskCompleteContract = new TaskCompleteContract();
                taskCompleteContract.setInnerCode(innerCode);
                taskCompleteContract.setTaskType(taskEntity.getProductTypeId());
                mqttProducer.send(topic, 2, taskCompleteContract);
            }
        }catch (Exception e){
            log.error("消息发送失败");
            e.printStackTrace();
            throw new LogicException("消息发送失败");
        }
    }

    @Override
    public List<TaskReportInfoVO> taskReportInfo(String start, String end) {

        LocalDateTime startTime = LocalDateTime.parse(start, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        LocalDateTime endTime = LocalDateTime.parse(end, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));

        List<TaskReportInfoVO> list = new ArrayList<>();
//        运营数据
//        工单总数
        Integer taskCountOp = taskCount(startTime, endTime, false, null);
//        完成工单数
        Integer taskCompleteCountOp = taskCount(startTime,endTime,false,VMSystem.TASK_STATUS_FINISH);
//        进行中工单数
        Integer taskProgessCountOp = taskCount(startTime,endTime,false,VMSystem.TASK_STATUS_PROGRESS);
//        拒绝工单数
        Integer taskCancelCountOp = taskCount(startTime,endTime,false,VMSystem.TASK_STATUS_CANCEL);
//        远程调用 运营人员总数
        Integer operatorCount = userServiceFeignClient.getOperatorCount();

        TaskReportInfoVO taskReportInfoVOOP = new TaskReportInfoVO();
        taskReportInfoVOOP.setRepair(false);
        taskReportInfoVOOP.setTotal(taskCountOp);
        taskReportInfoVOOP.setCompletedTotal(taskCompleteCountOp);
        taskReportInfoVOOP.setCancelTotal(taskCancelCountOp);
        taskReportInfoVOOP.setProgressTotal(taskProgessCountOp);
        taskReportInfoVOOP.setWorkerCount(operatorCount);


//        运维数据
//        工单总数
        Integer taskCountRe = taskCount(startTime,endTime,true,null);
//        完成工单数
        Integer taskCompleteCountRe = taskCount(startTime,endTime,true,VMSystem.TASK_STATUS_FINISH);
        //        进行中工单数
        Integer taskProgessCountRe = taskCount(startTime,endTime,true,VMSystem.TASK_STATUS_PROGRESS);
//        拒绝工单数
        Integer taskCancelCountRe = taskCount(startTime,endTime,true,VMSystem.TASK_STATUS_CANCEL);
//        远程调用 运维人员总数
        Integer repairerCount = userServiceFeignClient.getRepairerCount();

        TaskReportInfoVO taskReportInfoVORe = new TaskReportInfoVO();
        taskReportInfoVORe.setRepair(true);
        taskReportInfoVORe.setTotal(taskCountRe);
        taskReportInfoVORe.setCompletedTotal(taskCompleteCountRe);
        taskReportInfoVORe.setCancelTotal(taskCancelCountRe);
        taskReportInfoVORe.setProgressTotal(taskProgessCountRe);
        taskReportInfoVORe.setWorkerCount(repairerCount);

        list.add(taskReportInfoVOOP);
        list.add(taskReportInfoVORe);
        return list;
    }

    /**
     * 创建自动维修工单
     * @param statusContract
     */
    @Override
    public void createRepairTaskAuto(VmStatusContract statusContract) {
        String innerCode = statusContract.getInnerCode();

        List<StatusInfo> statusInfoList = statusContract.getStatusInfo();

        boolean b = statusInfoList.stream().anyMatch(statusInfo -> statusInfo.isStatus() == false);
        if(!b){
            log.info("售货机没有问题！");
            return ;
        }
//        远程调用，根据售货机编号查询售货机数据
        VmVO vmVO = vmServiceFeignClient.getvmInfoByInnerCode(innerCode);
        if(vmVO == null){
            log.error("没有获取到售货机数据");
            throw new LogicException("没有获取到售货机数据");
        }
        Integer userId = this.getLeastUser(vmVO.getRegionId(), VMSystem.TASK_TYPE_REPAIR);
        if(userId == null){
            log.error("没有获取用户");
            throw new LogicException("没有获取用户");
        }
//        判断当前售货机，是否有未完成的同类工单
        this.hasTask(innerCode,VMSystem.TASK_TYPE_REPAIR);
        try {
//        创建工单
            TaskViewModel taskViewModel = new TaskViewModel();
            taskViewModel.setCreateType(0);//自动
            taskViewModel.setInnerCode(innerCode);
            taskViewModel.setUserId(userId);//当天区域内工单数量最少的用户id
            taskViewModel.setProductType(VMSystem.TASK_TYPE_REPAIR);
            taskViewModel.setDesc(JsonUtil.serialize(statusInfoList));
            this.create(taskViewModel, 0);
        }catch (Exception e){
            e.printStackTrace();
        }

    }

    /**
     * 自动创建补货工单
     * @param contract
     */
    @Override
    public void createSupplyAuto(SupplyContract contract) {
        String innerCode = contract.getInnerCode();
        List<SupplyChannel> supplyChannelList = contract.getSupplyData();
//        远程调用，根据售货机编号查询售货机数据
        VmVO vmVO = vmServiceFeignClient.getvmInfoByInnerCode(innerCode);
        if(vmVO == null){
            log.error("没有获取到售货机数据");
            throw new LogicException("没有获取到售货机数据");
        }
//        获取工单最少的运营人员
        Integer userId = this.getLeastUser(vmVO.getRegionId(), VMSystem.TASK_TYPE_SUPPLY);
        List<TaskDetailsViewModel> detailsViewModelList = supplyChannelList.stream().map(supplyChannel -> {
            TaskDetailsViewModel taskDetailsViewModel = new TaskDetailsViewModel();
            taskDetailsViewModel.setChannelCode(supplyChannel.getChannelCode());
            taskDetailsViewModel.setExpectCapacity(supplyChannel.getCapacity());
            taskDetailsViewModel.setSkuId(supplyChannel.getSkuId().toString());
            taskDetailsViewModel.setSkuName(supplyChannel.getSkuName());
            taskDetailsViewModel.setSkuImage(supplyChannel.getSkuImage());
            return taskDetailsViewModel;
        }).collect(Collectors.toList());
//        创建工单
        TaskViewModel taskViewModel = new TaskViewModel();
        taskViewModel.setCreateType(0);//自动
        taskViewModel.setInnerCode(innerCode);
        taskViewModel.setUserId(userId);//当天区域内工单数量最少的用户id
        taskViewModel.setProductType(VMSystem.TASK_TYPE_SUPPLY);
        taskViewModel.setDesc("补货");
        taskViewModel.setDetails(detailsViewModelList);
        this.create(taskViewModel,0);
    }

    private Integer taskCount(LocalDateTime startTime, LocalDateTime endTime, boolean isRepair, Integer taskStatus) {

        LambdaQueryWrapper<TaskEntity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper
                .ge(TaskEntity::getUpdateTime,startTime)
                .le(TaskEntity::getUpdateTime,endTime)
                .eq(taskStatus != null,TaskEntity::getTaskStatus,taskStatus);

        if(isRepair){
//            运维工单
            queryWrapper.ne(TaskEntity::getProductTypeId,VMSystem.TASK_TYPE_SUPPLY);
        }else{
//            运营工单
            queryWrapper.eq(TaskEntity::getProductTypeId,VMSystem.TASK_TYPE_SUPPLY);
        }

        int count = count(queryWrapper);
        return count;

    }

    /**
     * 创建工单编号
     *
     * @return
     */
    private String generateCode() {

//        获取当前的年月日
        String date = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"));

        String key = "lkd:task:code:" + date;
//        获取当天递增的序号
        long value = redisTemplate.opsForValue().increment(key, 1);
        redisTemplate.expire(key, 1, TimeUnit.DAYS);

        String code = date + Strings.padStart(String.valueOf(value), 4, '0');
        log.info("code={}", code);
        return code;
    }

    /**
     * 检查是否收货机有未完成的同类工单
     *
     * @param innerCode
     * @param productType
     */
    private void hasTask(String innerCode, Integer productType) {

//        查询工单表
//        select * from tb_task where task_status < 3 and productTypeId =? and innerCode=?
        LambdaQueryWrapper<TaskEntity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper
                .lt(TaskEntity::getTaskStatus, VMSystem.TASK_STATUS_CANCEL)
                .eq(TaskEntity::getProductTypeId, productType)
                .eq(TaskEntity::getInnerCode, innerCode);
        int count = count(queryWrapper);
        if (count > 0) {
            log.error("存在未完成的同类工单，结束");
            throw new LogicException("存在未完成的同类工单，结束");
        }
    }

    /**
     * 检查工单类型和售货机状态
     *
     * @param productType
     * @param vmStatus
     */
    private void checkVmStatus(Integer productType, Integer vmStatus) {
        if (productType == VMSystem.TASK_TYPE_DEPLOY &&
                vmStatus != VMSystem.VM_STATUS_NODEPLOY) {
//            投放工单,售货机不是未投放状态
            log.error("售货机不是未投放状态");
            throw new LogicException("售货机不是未投放状态");
        }
        if (productType == VMSystem.TASK_TYPE_SUPPLY &&
                vmStatus != VMSystem.VM_STATUS_RUNNING) {
            log.error("售货机不是运营状态");
            throw new LogicException("售货机不是运营状态");
        }
        if (productType == VMSystem.TASK_TYPE_REVOKE &&
                vmStatus != VMSystem.VM_STATUS_RUNNING) {
            log.error("售货机不是运营状态");
            throw new LogicException("售货机不是运营状态");
        }
    }

    /**
     * 更新redis中 工单的数量
     *
     */
    private void updateRedisTaskNum(TaskEntity taskEntity,Long score){

//        根据工单类型，得出rolecode员工角色
        Integer productTypeId = taskEntity.getProductTypeId();
        String roleCode = productTypeId == VMSystem.TASK_TYPE_SUPPLY?"1002":"1003";
        String key = VMSystem.getRegionTaskKey(taskEntity.getRegionId(),roleCode);
        String value = taskEntity.getUserId().toString();
//        更新工单数量
        redisTemplate.opsForZSet().incrementScore(key,value,score);
    }

    /**
     * 自动创建工单，选择工单量最少用户
     * @return
     */
    private Integer getLeastUser(Long regionId,Integer productTypeId){
//        用户角色
        String roleCode = productTypeId == VMSystem.TASK_TYPE_SUPPLY?"1002":"1003";
        String key = VMSystem.getRegionTaskKey(regionId,roleCode);
//        查询工单量最少的用户,按照score正序排序,第一个
        Set<String> set = redisTemplate.opsForZSet().range(key, 0, 0);
        if(CollectionUtils.isEmpty(set)){
            log.error("没有获取到工单最少的用户");
            return null;
        }
        String value = set.stream().findFirst().get();
        return Integer.valueOf(value);


    }
}
